from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from myapp.models import Users

# Create your views here.
def index(request):
    # #----------执行model的操作 增加数据
    # ob = users() #实例化一个新对象
    # ob.name = "张三"
    # ob.age = 20
    # ob.phone = '123565'
    # ob.save() #新对象就是添加，已存在对象则是修改
    # return HttpResponse("首页")
    # #-----------删除操作
    # mod = users.objects #获取user的model对象
    # user = mod.get(id=2) #获取id=2的数据信息
    # user.delete()#执行删除操作
    # #------------修改操作
    # ob = users.objects.get(id=1)
    # #print(ob.name)
    # ob.name="小明"
    # ob.age = 26
    # ob.save()
    #数据查询
    # mod = users.objects
    # info = mod.all()#查询所有数据
    # ulist = mod.filter(name='小五')#获取指定数据
    # agee = mod.filter(age_gt=22)#获取age大于22信息 gte（大于等于） lte(小于等于)
    # order = mod.order_by("age")#按age升序排序 进行数据查询
    # for u in ulist:
    #     print(u.id,u.name,u.age,u.phone)
    return HttpResponse("首页 <br/><a href='/users'>用户</a>")

# def intt(request,sid):
#     return HttpResponse("随便输入整数,为"+"%d"%(sid))

#游览用户信息
def indexuser(request):
    # try:
        ulist = Users.objects.all()
        context = {'userslist':ulist}
        return render(request,"myapp/users/index.html",context)#加载模版并且放入数据
    # except:
    #     return HttpResponse("没有找到用户信息!")
#加载添加用户信息表单
def adduser(rq):
    return render(rq,"myapp/users/add.html")
#执行用户信息添加
def insertuser(rq):
    try:
        ob = Users()
        #从表单中获取要添加的信息 封装到ob对象中
        ob.name = rq.POST['name']
        ob.age = rq.POST['age']
        ob.phone = rq.POST['phone']
        ob.save()
        context = {"info":"添加成功！"}
    except:
        context = {"info":"添加失败！"}

    return render(rq,"myapp/users/info.html",context)
##执行用户信息删除
def deluser(rq,uid=0):
    try:
        ob =Users.objects.get(id=uid) #获取要删除的数据的id
        ob.delete()
        context = {"info": "删除成功！"}
    except:
        context = {"info": "删除失败！"}


    return render(rq, "myapp/users/info.html", context)
#加载用户并修改
def edituser(rq,uid=0):
    try:
        ob = Users.objects.get(id=uid)  # 获取要修改的数据的id
        context = {"user": ob}
        return render(rq, "myapp/users/edit.html", context)
    except:
        context = {"info": "没有找到修改数据！"}


#执行用户信息修改
def updateuser(rq):
    try:
        uid = rq.POST['id']
        ob = Users.objects.get(id=uid)
        # 从表单中获取要添加的信息 封装到ob对象中
        ob.name = rq.POST['name']
        ob.age = rq.POST['age']
        ob.phone = rq.POST['phone']
        ob.save()
        context = {"info": "修改成功！"}
    except:
        context = {"info": "修改失败！"}

    return render(rq, "myapp/users/info.html", context)